package com.xt.back.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xt.back.dto.CourseMappingDto;
import com.xt.back.entity.CourseMapping;
import com.xt.back.mapper.CourseMapper;
import com.xt.back.mapper.CourseMappingMapper;
import com.xt.back.mapper.UserMapper;
import com.xt.back.service.ICourseMappingService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 用户课程关联表 服务实现类
 * </p>
 *
 * @author leotong
 * @since 2022-04-03
 */
@Service
@AllArgsConstructor
public class CourseMappingServiceImpl extends ServiceImpl<CourseMappingMapper, CourseMapping> implements ICourseMappingService {

    private final CourseMappingMapper courseMappingMapper;
    private final CourseMapper courseMapper;
    private final UserMapper userMapper;

    @Override
    public Page<CourseMappingDto> getCourseMappingByPage(CourseMapping courseMapping) {
        Page<CourseMapping> page=new Page<>();
        Page<CourseMappingDto> result=new Page<>();
        QueryWrapper<CourseMapping> queryWrapper=new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(courseMapping.getCourseId()!=null&&!Objects.equals(courseMapping.getCourseId(),""),CourseMapping::getCourseId,courseMapping.getCourseId())
                .eq(courseMapping.getUserId()!=null&&!Objects.equals(courseMapping.getUserId(),""),CourseMapping::getUserId,courseMapping.getUserId());
        Page<CourseMapping> mappingPage = courseMappingMapper.selectPage(page, queryWrapper);
        result.setTotal(mappingPage.getTotal());
        System.out.println(result.getTotal());
        result.setRecords(convert(mappingPage.getRecords()));
        return result;
    }

    @Override
    public List<CourseMappingDto> getAllCourseMapping() {
        return convert(this.list());
    }

    public List<CourseMappingDto> convert(List<CourseMapping> courseMappings){
        List<CourseMappingDto> result=new ArrayList<>();
        for (CourseMapping courseMapping : courseMappings) {
            CourseMappingDto courseMappingDto=new CourseMappingDto(
                    courseMapping.getId(),
                    courseMapper.selectById(courseMapping.getCourseId()),
                    userMapper.selectById(courseMapping.getUserId())
            );
            courseMappingDto.setCreateTime(courseMapping.getCreateTime());
            result.add(courseMappingDto);
        }
        return result;
    }
}
